<template>
  <el-dialog
      title="添加人员"
      v-model="showDialog"
      width="400px"
      @close="handleClose"
  >
    <el-form :model="author" label-width="80px">
      <el-form-item label="人名/账号">
        <el-select
            filterable
            allow-create
            v-model="author_name_username">
          <el-option v-for="item in author_list"
                     :key="item.username"
                     :label="`${item.name} (${item.username})`"
                     :value="JSON.stringify({name: item.name, username: item.username})">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分数比例"  >
        <el-input v-model="author.weight" placeholder="分多少比值的分给此人员(小数)"/>
      </el-form-item>
    </el-form>
<!--    添加一个提示信息有四行-->
    <div class="el-dialog__body">
      <span style="color: #999999;">
        负责人必须为第一人员否则会自动修改。<br/>
        负责人只能有一位，否则添加失败<br/>
        所有人员的分数比例之和必须为1<br/>
        分数比例为(0,1]区间内的数值<br/>
      </span>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps } from 'vue';
import { ElMessage } from "element-plus";

// 定义props和emits
const props = defineProps({
  currentMembers: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['add-author']);

const showDialog = ref(false);
const author = ref({
  name: '',
  username: '',
  weight: null,
});
const author_name_username = ref(null);
const author_list = ref([]);

// 打开对话框
const open = () => {
  showDialog.value = true;
  const alluser = localStorage.getItem('alluser');
  author_list.value = JSON.parse(alluser);
  const userinfoString = localStorage.getItem('userinfo');
  const userinfo = JSON.parse(userinfoString);

  // 如果当前没有成员，设置默认负责人
  if (props.currentMembers.length === 0) {
    author.value.name = userinfo['name'];
    author.value.username = userinfo['username'];
    author.value.weight = null;
    author_name_username.value = JSON.stringify({
      name: userinfo['name'],
      username: userinfo['username']
    });
  } else {
    // 重置表单
    author.value = { name: '', username: '', weight: null };
    author_name_username.value = null;
  }
};

const handleClose = () => {
  showDialog.value = false;
};

const confirm = () => {
  try {


    // 解析选中的用户
    if (author_name_username.value) {
      const selectedUser = JSON.parse(author_name_username.value);
      author.value.username = selectedUser.username;
      author.value.name = selectedUser.name;
    } else {
      ElMessage.error('请选择人员');
      return;
    }
// 验证权重
    if (author.value.weight) {
      const weight = parseFloat(author.value.weight);
      if (isNaN(weight)) {
        ElMessage.error('分数比例必须是数字');
        return;
      }
      if (weight <= 0 || weight > 1) {
        ElMessage.error('分数比例必须在(0,1]区间内');
        return;
      }
      //权重相加小于1
      // 计算权重和
      let sum_weight = props.currentMembers.reduce((sum, member) => sum + member.weight, 0)+ weight;

      if (sum_weight > 1) {
        ElMessage.error('分数比例之和不能超过1');
        return;
      }else{
        // 计算当前权重和
        ElMessage.warning('还有'+((1-sum_weight)*100)+"%的分数没有分配")
      }
    }else{
      ElMessage.warning('没有填写分数比例');
      return;
    }
    // 使用emit传递新作者
    emit('add-author', { ...author.value });

    handleClose();
  } catch (e) {
    ElMessage.error('添加失败,请检查网络或刷新后重试：' + e);
  }
};

defineExpose({
  open,
});
</script>